<template lang="pug">
  .CreateCommercialWagesModal
    Modal(
      v-model="isShowCreateCommercialWagesModal"
      :title="actionType === 'view' ? '查看商保待遇' : (actionType === 'edit' ? '修待遇环节' : '新增待遇环节')"
      class-name="vertical-center-modal"
      width="900"
    )
      .clearfix
        Form.ivu-row.has-rules-item2(ref="formData" :model="formData" :rules="rules" :label-width="130"  v-if="liveNode")
          FormItem.form-item.ivu-col(v-for="(item, index) of formItem" :label="item.label" :key="index" :class="item.style" :prop="item.prop")
            template(v-if="item.type === 'input'")
              Input(v-model="formData[item.model]" :placeholder="actionType === 'view' ? '未填写' : item.placeholder" :disabled="actionType === 'view' || item.isDisabled" clearable)
            template(v-if="item.type === 'select'")
              Select(v-if="item.fn" v-model="formData[item.model]" :placeholder="actionType === 'view' ? '未填写' : item.placeholder" :disabled="actionType === 'view' || item.isDisabled" clearable filterable @on-change="listenCall(item.fn, item.model, $event)")
                Option(v-for="(c_item, c_index) of arrListDown[item.options]" :key="c_index" :value="c_item.label") {{c_item.value}}
              Select(v-else v-model="formData[item.model]" :placeholder="actionType === 'view' ? '未填写' : item.placeholder" :disabled="actionType === 'view' || item.isDisabled" clearable filterable)
                Option(v-for="(c_item, c_index) of arrListDown[item.options]" :key="c_index" :value="c_item.label") {{c_item.value}}
            template(v-if="item.type === 'switch'")
              i-switch(v-model="formData[item.model]" :disabled="actionType === 'view'")
            template(v-if="item.type === 'radio'")
              RadioGroup.beautiful-radio-group(type="button" v-model="formData[item.model]"  @on-change="listenCall(item.fn, item.model, $event)")
                Radio.display-inline-block(v-for="c_item of item.radioArr" :label="c_item.value" :disabled="item.isDisabled") {{c_item.label}}
            template(v-if="item.type === 'cascader'")
              .areaTrees
                Cascader(v-model="formData[item.model]" :data="areaTree" clearable change-on-select @on-change="areaTreeChange(item.model, $event)" :disabled="actionType === 'view' || item.isDisabled")
            template(v-if="item.type === 'inputnumber'")
              Input(v-model="formData[item.model]" type="number" :placeholder="actionType === 'view' ? '未填写' : item.placeholder" :disabled="actionType === 'view' || item.isDisabled" clearable)
            template(v-if="item.type === 'interval'")
              DatePicker.pull-left.interval-date(v-model="formData[item.model1]" :placeholder="actionType === 'view' ? '未填写' : item.placeholder1" type="date" @on-change="handleChangeDatePicker(item.model1, $event)" :disabled="actionType === 'view'")
              span.pl-10.pr-10.pull-left.line-h-32 --
              DatePicker.pull-left.interval-date(v-model="formData[item.model2]" :placeholder="actionType === 'view' ? '未填写' : item.placeholder2" type="date" @on-change="handleChangeDatePicker(item.model2, $event)" :disabled="actionType === 'view'")


      .clearfix(slot="footer")
        Button(type="text" @click="cancel") 取消
        Button(v-if="actionType !== 'view'" type="primary" @click="handleSave" :loading="!isCanSubmit") 确定
</template>

<script>
import { Common } from '@/utils/common.js'
import dataApi from '@/api/data.js'
import { TreatmentApi } from '@/api/Treatment.api.js'
import _cloneDeep from 'clone-deep'
import { ProvinceList, AreaTree } from '@/utils/publicJson.js'
import { constants } from 'fs';
import { TreatmentBasicsTypeApi } from '@/api/TreatmentBasicsType.api.js'
import { TreatmentBasicsLinkApi } from '@/api/TreatmentBasicsLink.api.js'
export default {
  name: 'CreateCommercialWagesModal',

  props: [],

  watch: {
  },

  computed: {
  },

  data () {
    return {
      liveNode: true,
      isShowCreateCommercialWagesModal: false,
      isCreate: true, 
      actionType: 'view',
      wagesId: '',
      useArea: true,
      formData: {
        id: '',
        insuredTypeId: '',
        treatmentTypeId: '',
        linkName:'',
        linkExplain:'',
        applyRange: '0',
        sysAreaId: [],
        personLiableType: '',
        appointPersonLiableId: '',
        handlingDays: '',
        linkSort: '0',
        linkStatus: true
      },
      formItem: [
        { type: 'select', label: '参保险种', placeholder: '请选择参保险种', prop: 'insuredTypeId', model: 'insuredTypeId', style: 'ivu-col-span-12', options: 'insuredTypeId', fn: 'selectChange', isDisabled: false },
        { type: 'select', label: '待遇名称', placeholder: '请选择参待遇名称', prop: 'treatmentTypeId', model: 'treatmentTypeId', style: 'ivu-col-span-12', options: 'treatmentTypeId', fn: 'selectChange', isDisabled: false },
        { type: 'input', label: '环节名称：', placeholder: '请输入环节名称', prop: 'linkName', model: 'linkName', style: 'ivu-col-span-12', isDisabled: false },
        { type: 'input', label: '环节说明：', placeholder: '请输入环节说明', prop: 'linkExplain', model: 'linkExplain', style: 'ivu-col-span-12', isDisabled: false },
        { type: 'radio', label: '适用范围：', placeholder: '请选择适用范围', prop: 'applyRange', model: 'applyRange', isDisabled: false, style: 'ivu-col-span-12',fn: 'areaChange', radioArr: [{ value: '0', label: '全国' }, { value: '1', label: '具体地区' }] },
        { type: 'cascader', label: '具体地区：', placeholder: '请输入具体地区', prop: 'sysAreaId', model: 'sysAreaId', style: 'ivu-col-span-12', isDisabled: true },
        { type: 'select', label: '负责人：', placeholder: '请选择负责人', prop: 'personLiableType', model: 'personLiableType', options: 'personLiableType', fn: 'personLiableTypeChange', style: 'ivu-col-span-12', isDisabled: false },
        { type: 'select', label: '主要负责人：', placeholder: '请输入主要负责人', prop: 'appointPersonLiableId', model: 'appointPersonLiableId', options: 'appointPersonLiableId', fn:'appointPersonLiableIdChange',style: 'ivu-col-span-12', isDisabled: true },
        { type: 'inputnumber', label: '办理天数', placeholder: '请输入办理天数', prop: 'handlingDays', model: 'handlingDays', style: 'ivu-col-span-12', isDisabled: false },
        { type: 'select', label: '排序', placeholder: '请选择排序，不选默认排首位', prop: 'linkSort', model: 'linkSort', options: 'linkSort', style: 'ivu-col-span-12', isDisabled: false },
        { type: 'switch', label: '启用状态', placeholder: '', prop: 'linkStatus', model: 'linkStatus',style: 'ivu-col-span-24' }
      ],
      
      rules: {
        insuredTypeId: [
          { required: true, message: '请选择参保险种', trigger: 'change' }
        ],
        treatmentTypeId: [
          { required: true, message: '请选择参待遇名称', trigger: 'change' }
        ],
        linkName: [
          { required: true, message: '请输入环节名称', type: 'string',trigger: 'blur' }
        ],
        linkExplain: [
          { required: true, message: '请输入环节说明', type: 'string', trigger: 'blur' }
        ],
        applyRange: [
          { required: true, message: '请选择适用范围', type: 'string', trigger: 'change' }
        ],
        sysAreaId: [
          // { required: true, message: '请输入地区', type: 'array', trigger: 'change' }
        ],
        personLiableType: [
          { required: true, message: '请选择负责人', type: 'string', trigger: 'change' }
        ],
        appointPersonLiableId: [

        ],
        handlingDays: [
          { required: true, message: '请输入办理天数', type: 'string', trigger: 'blur' }
        ]
      },
      areaTree: AreaTree,
      arrListDown: {
        treatmentTypeId: [],
        tempOps: [],
        commercialData: [],
        employeeList: [],
        personLiableType: [],
        linkSort: [],
        appointPersonLiableId:[]
      },
      isCanSubmit: true,
      queryCommercialData: [],
      queryEmployeeList: []
    }
  },

  mounted () {
    this.getPersonLiableType()
    this.getUserNameList()
  },

  methods: {
     // 所在地区选择
    areaTreeChange (model, value) {
      console.log(model,value,'所在地区选择')
      this.formData[model] = value
    },

    cancel () {
      this.isShowCreateCommercialWagesModal = false
    },

    show (actionType, id) {
      this.isCanSubmit = true
      if (!id) {
        this.rules.sysAreaId.shift()
        this.formItem[5].style = 'ivu-col-span-12 remove-required'
        this.formItem[5].isDisabled = true
        this.formItem[0].isDisabled = false
        this.formItem[1].isDisabled = false
      } else {
        this.formItem[0].isDisabled = true
        this.formItem[1].isDisabled = true
      }
      this.actionType = actionType
      console.log('actionType: ', actionType, 'id: ', id)
      this.formData.id = id ? id : ''
      this.isShowCreateCommercialWagesModal = true
      this.$refs.formData.resetFields()
      console.log('this.arrListDown: ', this.arrListDown)
    },

    // 监听所有调用的方法
    listenCall (methodsWords, ...values) {
      this[methodsWords](...values)
    },
    
    // 负责人
    async getPersonLiableType () {
      let res = await TreatmentBasicsLinkApi.getPersonLiableType()
      console.log('获取负责人res: ', res)
      if (res.status === 200 && res.data.success) {
        var result = res.data.data
        for (var i in result) {
          result[i].label = result[i].value
          result[i].value =  result[i].text
        }
        this.arrListDown.personLiableType = result
      }
      // this.arrListDown.personLiableType = [{label:1,value:'所属客服'},{label:2,value:'客户'},{label:3,value:'员工'},{label:4,value:'指定负责人'}]
    },

    // 主要负责人列表
    async getUserNameList () {
      let res = await TreatmentBasicsLinkApi.getUserNameList({name:''})
      console.log('获取负责人res: ', res)
      if (res.status === 200 && res.data.success) {
        var result = res.data.data
        for (var i in result) {
          result[i].label = result[i].id
          result[i].value =  result[i].name
        }
        this.arrListDown.appointPersonLiableId = result
      }
    },

    appointPersonLiableIdChange (model, val) {
      this.formData[model] = val
    },

    // 客户名称改变
    companyIdChange (model, val) {
      console.log('客户名称改变model: ', model, ', val: ', val)
      this.getEmployeeListNew(val)
    },

    // 获取员工下拉内容
    async getEmployeeListNew (id) {
      var params = {
        CompanyID: id,
        BeHiring: 1,
        PageIndex: 1,
        PageSize: 1000
      }
      let res = await TreatmentApi.getEmployeeListNew(params)
      console.log('res: ', res)
      if (res.status === 200 && res.data.success) {
        this.queryEmployeeList = res.data.data
        this.arrListDown.employeeList = res.data.data.map(item => {
          return { label: item.name, value: item.id }
        })
      }
    },

    // 负责人改变
    personLiableTypeChange (model, val) {
      this.liveNode = false
      let formItem = this.formItem
      let rules = this.rules
      console.log(model, val, '负责人改变')
      this.formData[model] = val
      for (var i in formItem) {
        if (formItem[i].prop == 'appointPersonLiableId') {
          formItem[i].isDisabled = val != '4'
        }
      }
      // 改变rules
      if (val == '4') {
        rules.appointPersonLiableId = [{ required: true, message: '请输主要负责人', type: 'string', trigger: 'blur' }]
        this.formItem[7].style = 'ivu-col-span-12 is-required'
      } else {
        this.formData.appointPersonLiableId = ''
        rules.appointPersonLiableId = []
        this.formItem[7].style = 'ivu-col-span-12 remove-required'
      }
      this.rules = rules
      this.formItem = formItem
      this.appointPersonLiableIdChange('appointPersonLiableId',this.formData['appointPersonLiableId'])
      this.$forceUpdate()
      this.liveNode = true
    },

    // 区域改变
    areaChange (model, val) {
      console.log(model,val,'areachange')
      this.formData[model] = val
      this.liveNode = false
      let formItem = this.formItem
      let rules = this.rules
      for (var i in formItem) {
        if (formItem[i].prop == 'sysAreaId') {
          formItem[i].isDisabled = val != 1
        }
      }
      // 改变rules
      if (val == 1) {
        rules.sysAreaId=[{ required: true, message: '请输入地区', type: 'array', trigger: 'change' }]
        this.formItem[5].style = 'ivu-col-span-12 is-required'
      } else {
        this.formData.sysAreaId = []
        rules.sysAreaId = []
        this.formItem[5].style = 'ivu-col-span-12 remove-required'
      }
      this.rules = rules
      console.log('改变rules',rules.sysAreaId)
      this.formItem = formItem
      this.$forceUpdate()
      this.liveNode = true
    },

    // 业务类型改变
    async selectChange (model, val) {
      if (!val) {
        return
      }
      console.log('val: ', val , model)
      console.log('业务类型改变_________________________________________')
      if (model === 'insuredTypeId') {
        this.getTreatmentTypeId(val)
        this.formData.treatmentTypeId = ''
        this.formData.linkSort = null
        this.arrListDown.linkSort = []
        if (val == 'FE566BF6-2CBB-42B6-8868-3363D6465DCB') {
          this.formItem[4].isDisabled = true
          console.log(this.formItem,this.formItem[4])
          this.applyRange = '0'
          this.areaChange('applyRange', '0')
        } else {
          this.formItem[4].isDisabled = false
        }
      } else if (model === 'treatmentTypeId') {
        this.formData.linkSort = '0'
        this.arrListDown.linkSort = []
        this.getSortList(val)
      }
      // if (model === 'insuredTypeId') {
      //   var selectInsuredTypeId = this.arrListDown.insuredTypeId.find(item => {
      //     return item.label === val
      //   })
      //   console.log('selectInsuredTypeId: ', selectInsuredTypeId)
      //   if (selectInsuredTypeId != undefined) {
      //     this.formData.employeeIdCardNo = selectEmployee.idCardNo ? selectEmployee.idCardNo + '' : ''
      //   }
      // }
      // var params = {
      //   EmployeeID: this.formData.employeeID,
      //   TreatmentParameterId: this.formData.treatmentParameterId
      // }
      // if (this.formData.employeeID && this.formData.treatmentParameterId !== '') {
      //   let res = await TreatmentApi.getTreatmentEnjoyEmployeeCommercial(params)
      //   if (res.data.success) {
      //     this.queryCommercialData = res.data.data.commercialData
      //     this.formData.employeeName = res.data.data.employeeData.name
      //     this.arrListDown.commercialData = res.data.data.commercialData.map(item => {
      //       return { label: item.securityNO, value: item.id }
      //     })
      //   }
      // }
    },

    // 日期选择
    handleChangeDatePicker (model, val) {
      this.formData[model] = val
    },

    // 根据ID获取待遇参数
    async getModel (id) {
      let res = await TreatmentBasicsLinkApi.getModel({id: id})
      console.log('根据ID获取待遇参数: ', res)
      if (res.data.success) {
        var result = res.data.data
        // this.formData.securityCompanyName = result.securityCompanyName
        Object.keys(this.formData).forEach(key => {
          if (result[key] == null) {return}
          if (key == 'sysAreaId') {
            result[key] = [result[key]]
            if (result['fullParentGUID']){
              let arr = result['fullParentGUID'].split('.')
              result[key].unshift(arr[arr.length-1])
              if (arr.length > 3) {
                result[key].unshift(arr[arr.length-2])
              }
            }
          }
          
          this.formData[key] = result[key]
        })

        this.getTreatmentTypeId(this.formData['insuredTypeId'])
        this.getSortList(this.formData['treatmentTypeId'])
        this.formData['linkStatus'] = this.formData['linkStatus'] == 0
        this.formData['linkSort'] = this.formData['linkSort']+''
        this.formData['personLiableType'] = this.formData['personLiableType']+''
        this.formData['handlingDays'] = this.formData['handlingDays']+''
        this.formData['applyRange'] = this.formData['applyRange']+''
        this.formData['appointPersonLiableId'] = this.formData['appointPersonLiableId'] ? this.formData['appointPersonLiableId'].toLowerCase():this.formData['appointPersonLiableId']
        this.areaChange('applyRange', this.formData['applyRange'])
        this.personLiableTypeChange('personLiableType', this.formData['personLiableType'])
        if (this.formData.insuredTypeId.toUpperCase() == 'FE566BF6-2CBB-42B6-8868-3363D6465DCB') {
            this.formItem[4].isDisabled = true
            console.log(this.formItem,this.formItem[4])
            this.applyRange = '0'
            this.areaChange('applyRange', '0')
          } else {
            this.formItem[4].isDisabled = false
          }
      } else {
        this.$Message.error({
          content: res.data.message,
          duration: 10,
          closable: true
        })
      }
    },

    // 保存
    handleSave () {
      this.$refs.formData.validate((valid) => {
        if (valid) {
          this.isCanSubmit = false
          console.log('this.formData: ', this.formData)
          var params = {...this.formData}
          params.linkStatus = params.linkStatus ? 0 : 1
          params.sysAreaId = params.sysAreaId ? params.sysAreaId[params.sysAreaId.length-1] : params.sysAreaId
          params.linkSort = params.linkSort ? params.linkSort : 0
          TreatmentBasicsLinkApi.save(params).then(res => {
            if (res.data.success) {
              this.$Message.success(res.data.message)
              this.isShowCreateCommercialWagesModal = false
              this.$emit('query')
            } else {
              this.isCanSubmit = true
              this.$Message.error({
                content: res.data.message,
                duration: 10,
                closable: true
              })
            }
          })
        }
      })
    },
    async getTreatmentTypeId (id) {
      var params = {
        insuredTypeId: id,
        HasPaging: true,
        PageIndex: 1,
        PageSize: 300
      }
      let res = await TreatmentBasicsTypeApi.getBasicsTypeList(params)
      console.log('客户薪资res: ', res)
      var result = res.data.data
      if (res.status === 200 && res.data.success) {
        for (var i in result) {
          result[i].label = result[i].value
          result[i].value = result[i].text
        }
        this.arrListDown.treatmentTypeId = result
        console.log(result)
        console.log(this.arrListDown.treatmentTypeId)
      } else {
        this.arrListDown.treatmentTypeId = []
        this.$Message.error({
          content: res.data.message,
          duration: 10,
          closable: true
        })
      }
      this.loading = false
    },
    async getSortList (id) {
      console.log('getsortlist_________',id)
      var params = {
        treatmentTypeId: id,
      }
      let res = await TreatmentBasicsLinkApi.getBasicsLinkSelectList(params)
      console.log('获取排序: ', res)
      var result = res.data.data
      if (res.status === 200 && res.data.success) {
        for (var i in result) {
          result[i].label = result[i].value
          result[i].value = result[i].text
        }
        this.arrListDown.linkSort = result
        console.log(result)
        console.log(this.arrListDown.treatmentTypeId)
      } else {
        this.arrListDown.linkSort = []
        this.$Message.error({
          content: res.data.message,
          duration: 10,
          closable: true
        })
      }
      this.loading = false
    },
  }
}
</script>

<style lang="less" scoped>

</style>
